#!/bin/sh
#
# run -- deploy a docker lab
#

lab_name=$1
lab_user=$2
lab_total=$3
# In hours
lab_life=$4

TOP_DIR=$(cd $(dirname $0)/../../ && pwd)
. $TOP_DIR/tools/docker/config $* >/dev/null

[ -z "$lab_identify" ] && lab_identify=1
[ -z "$lab_total" ] && lab_total=1
[ -z "$lab_user" ] && lab_user=ubuntu
[ -z "$lab_life" ] && lab_life=24H
[ -z "$lab_name" ] && lab_name=$CURRENT

[ ! -d $LAB_OUTPUT ] && mkdir -p $LAB_OUTPUT
VNC_IDENTIFY=1; [ $lab_identify -eq 0 ] && VNC_IDENTIFY=0

do_unlock
get_var HOST localhost
do_lock

# Start the transparent proxy via tinylab/cloud-ubuntu-proxy_client_transparent container
exist=`docker ps -q --filter=name=cloud-ubuntu-proxy_client_transparent | wc -l`
[ $exist -eq 0 -a $TPROXY -eq 1 -a -n "$PROXY_SERVER" -a -n "$PROXY_PWD" -a -n "$ENCRYPT_CMD" ] \
    && PROXY_SERVER=$PROXY_SERVER PROXY_PWD=$PROXY_PWD ENCRYPT_CMD=$ENCRYPT_CMD PROXY_LIMIT=$PROXY_LIMIT $DOCKER_TPROXY_CMD $*

# Start the ssh/vnc proxy via tinylab/cloud-ubuntu-web container
exist=`docker ps -q --filter=name=cloud-ubuntu-web | wc -l`
[ $exist -eq 0 ] && $DOCKER_EXPORT_CMD $*

OLD_TOP_DIR=$TOP_DIR
OLD_LAB_OUTPUT=$LAB_OUTPUT
for i in `seq 1 $lab_total`
do
    LAB_SRC=$OLD_TOP_DIR
    while :;
    do
       lab_name_random=`get_random`
       CONTAINER_NAME=${lab_name}-${lab_name_random}
       exist=`docker ps -q --filter=name=$CONTAINER_NAME | wc -l`
       [ $exist -eq 0 ] && break
    done

    LAB_PATH=${CONTAINER_NAME}+${lab_user}-${lab_life}-`date +"%Y%m%d-%H%M%S"`
    LAB_DST=$OLD_LAB_OUTPUT/$LAB_PATH/

    echo "LOG: Create $LAB_PATH"

    tmpfile=`mktemp`
    __lab_name=$lab_name
    [ "$lab_name" = "qing-lab" ] && __lab_name='*'
    find $LAB_SRC/configs/$lab_name \
         $LAB_SRC/labs/$__lab_name \
         $LAB_SRC/.git/modules/labs/$__lab_name \
         $LAB_SRC/tools -type f | sed -e "s%$LAB_SRC%./%g" | grep -v "/docker/\." > $tmpfile
    if [ "x$HOST_USER" = "xroot" ]; then
      rsync -arz $LAB_SRC $LAB_DST/ --files-from=$tmpfile
    else
      $SUDO -u $HOST_USER rsync -arz $LAB_SRC $LAB_DST/ --files-from=$tmpfile
    fi
    rm $tmpfile

    # Run it

    TOP_DIR=$LAB_DST
    . $TOP_DIR/tools/docker/config $lab_name >/dev/null

    do_unlock

    set_var CURRENT
    set_var HOST
    set_var VNC_IDENTIFY

    do_lock

    UNIX_USER=$lab_user CONTAINER_NAME=$CONTAINER_NAME $DOCKER_RUN_CMD $lab_name
done
